// ChatClientDoc.cpp : implementation file
//

#include "stdafx.h"
#include "Chat.h"
#include "ChatClientDoc.h"
#include "NatPunchthroughClient.h"
#include "ChatClientBaseDlg.h"
#include "ChatClientView.h"
// CChatClientDoc

IMPLEMENT_DYNCREATE(CChatClientDoc, CChatBaseDoc)

CChatClientDoc::CChatClientDoc()
: m_pNatPunchthroughClient(NULL)
, m_pUdpProxyClient(NULL)
{
}

BOOL CChatClientDoc::OnNewDocument()
{
	if (!CChatBaseDoc::OnNewDocument())
		return FALSE;

	m_pNatPunchthroughClient = new NatPunchthroughClient;

	AttachRaknetPlugin(m_pNatPunchthroughClient);

	m_pUdpProxyClient = new RakNet::UDPProxyClient;
	AttachRaknetPlugin(m_pUdpProxyClient);

	StartUpRaknet(MAX_CHAT_CLIENTS,30,&SocketDescriptor(), 1);	
	
	return TRUE;
}

CChatClientDoc::~CChatClientDoc()
{
	
	if (m_pNatPunchthroughClient)
	{
		DetachRaknetPlugin(m_pNatPunchthroughClient);
		delete m_pNatPunchthroughClient;
		m_pNatPunchthroughClient = NULL;
	}

	if (m_pUdpProxyClient)
	{
		DetachRaknetPlugin(m_pUdpProxyClient);
		delete m_pUdpProxyClient;
		m_pUdpProxyClient = NULL;
	}
}


BEGIN_MESSAGE_MAP(CChatClientDoc, CChatBaseDoc)
END_MESSAGE_MAP()


// CChatClientDoc diagnostics

#ifdef _DEBUG
void CChatClientDoc::AssertValid() const
{
	CChatBaseDoc::AssertValid();
}

#ifndef _WIN32_WCE
void CChatClientDoc::Dump(CDumpContext& dc) const
{
	CChatBaseDoc::Dump(dc);
}
#endif
#endif //_DEBUG

#ifndef _WIN32_WCE
// CChatClientDoc serialization

void CChatClientDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		// TODO: add storing code here
	}
	else
	{
		// TODO: add loading code here
	}
}


#endif


// CChatClientDoc commands

void CChatClientDoc::SwitchDlg( CChatClientBaseDlg& oldChatClientBaseDlg, CChatClientBaseDlg& newChatClientBaseDlg )
{	
	oldChatClientBaseDlg.EndDialog(0);

	POSITION pos = GetFirstViewPosition();

	reinterpret_cast<CChatClientView*>(GetNextView(pos))->SetActivateClientDlg(&newChatClientBaseDlg);
}

void CChatClientDoc::UseProxyModel( RakNet::UDPProxyClientResultHandler& resultHandler, const SystemAddress& proxyCoordinator, const SystemAddress& sourceAddress, const RakNetGUID& targetGuid, RakNetTimeMS timeoutOnNoDataMS, RakNet::BitStream *serverSelectionBitstream/*=0*/ )
{
	m_pUdpProxyClient->SetResultHandler(&resultHandler);
	m_pUdpProxyClient->RequestForwarding(proxyCoordinator, sourceAddress, targetGuid, timeoutOnNoDataMS, serverSelectionBitstream);
}

bool CChatClientDoc::UseHolePunchingModel( const RakNetGUID& destination, const SystemAddress& facilitator )
{
	return m_pNatPunchthroughClient->OpenNAT(destination, facilitator);
}

